package com.atguigu.lease.common.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author LOGIN
 * @title MinioConfig
 * @create 2025/6/24 11:45
 * @description
 */
@Configuration
@ConfigurationProperties(prefix = "minio")//容器创建配置对象时 会自动使用minio前缀匹配配置文件中的属性设置给自己的成员变量属性
@Data //自动设置属性 需要有getter方法
public class MinioConfig {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucket;
    @Bean
    public MinioClient minioClient() throws Exception {
        //1、创建minio客户端
        MinioClient minioClient = MinioClient.builder()
                //minio服务器地址
                .endpoint(this.endpoint)
                //minion账号密码
                .credentials(this.accessKey, this.accessKey)
                .build();
        //判断需要使用的桶是否存在
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(this.bucket)
                .build());

        if (!exists) {
            //桶不存在，新建桶
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(this.bucket)
                        .build());
            //桶的默认权限 private读写
            //修改桶的权限为 公共读 私有写
            String policy = """
                    {
                        "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::%s/*"
                        } ],
                        "Version" : "2012-10-17"
                    }
                    """.formatted(bucket); //使用bucket的值 填充字符串的占位符 最后返回字符串

            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(this.bucket)
                    .config("policy")
                    .build());
        }

        return minioClient;
    }


}
